<template>
	<div ref="chartRef" class="echartsClass"></div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const props = defineProps<{
	data: []
}>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
	if (!chartRef.value) {
		return
	}
	chartInstance?.dispose()
	chartInstance = echarts.init(chartRef.value)
	updateChart()
	window.addEventListener('resize', handleChartResize)
}

const chartData = {
	legendData: ['0-3月', '4-6月', '7-9月', '10月及以上'],
	seriesData: [
		{ value: 5, name: '0-3月' },
		{ value: 3, name: '4-6月' },
		{ value: 4, name: '7-9月' },
		{ value: 88, name: '10月及以上' }
	]
}

const updateChart = () => {
	if (!chartInstance) {
		return
	}
	const option = {
		title: {
			text: '结题阶段滞后时间分布'
		},
		tooltip: {
			trigger: 'item'
		},
		legend: {
			orient: 'vertical',
			left: 'right',
			data: chartData.legendData
		},
		series: [
			{
				name: '滞后次数',
				type: 'pie',
				radius: ['0%', '70%'],
				avoidLabelOverlap: false,
				label: {
					show: true,
					position: 'outside',
					formatter: '{b}: {c}'
				},
				emphasis: {
					label: {
						show: true,
						fontSize: '16',
						fontWeight: 'bold'
					}
				},
				labelLine: {
					show: true
				},
				data: chartData.seriesData
			}
		]
	}

	chartInstance.setOption(option)
}

const handleChartResize = () => {
	chartInstance?.resize()
}

const cleanupChart = () => {
	window.removeEventListener('resize', handleChartResize)
	chartInstance?.dispose()
}

onBeforeUnmount(() => {
	cleanupChart()
})

onMounted(() => {
	initChart()
})
</script>
<style lang="scss" scoped>
.echartsClass {
	width: 550px;
	height: 400px;
}
</style>
